﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PlanProd.Contracts.Misc;
using PlanProd.Contracts;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace WebAppPlanProduccion.Code
{
    public abstract class BasePage : System.Web.UI.Page
    {
        protected BaseMasterPage masterPage { get; set; }

        protected WebServiceHelper WebServiceHelper { get; set; }

        protected UIHelper UIHelper { get; set; }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Context.Session != null)
            {
                //Tested and the IsNewSession is more advanced then simply checking if 
                // a cookie is present, it does take into account a session timeout, because 
                // I tested a timeout and it did show as a new session
                if (Session.IsNewSession)
                {
                    // If it says it is a new session, but an existing cookie exists, then it must 
                    // have timed out (can't use the cookie collection because even on first 
                    // request it already contains the cookie (request and response
                    // seem to share the collection)
                    string szCookieHeader = Request.Headers["Cookie"];
                    if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        //Session.Abandon();
                        FormsAuthentication.SignOut();
                        Response.Redirect("/Account/Login.aspx");
                    }
                }
            }
        }

        protected override void OnPreLoad(EventArgs e)
        {
            masterPage = (BaseMasterPage)this.Master;

            WebServiceHelper = new WebServiceHelper();
            WebServiceHelper.ServiceOptionsDefault = new ServiceOptions();
            WebServiceHelper.ServiceOptionsDefault.UserName = BaseMasterPage.UserName;

            UIHelper = new UIHelper();
            UIHelper.companyId = BaseMasterPage.CompanyId;
            UIHelper.WebServiceHelper = WebServiceHelper;

            masterPage.PreLoad(WebServiceHelper.GetOperationsForUser(BaseMasterPage.ApplicationId, BaseMasterPage.CompanyId, User.Identity.Name));
            //masterPage.PreLoad(new List<string>());

            base.OnPreLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            // Aplica seguridad a los botones
            ApplySecurity();
            base.OnPreRender(e);
        }

        /// <summary>
        /// Aplica la seguridad en los botones a la pantalla
        /// </summary>
        protected virtual void ApplySecurity()
        {
        }

        /// <summary>
        /// Testea si el usuario tiene permisos para la operación
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        public bool HasPermissionFor(string operation)
        {
            return masterPage.HasPermissionFor(operation);
        }

        protected void HasPermissionToSeeMe(string operation)
        {
            if (!BaseMasterPage.IsAdmin && !HasPermissionFor(operation))
            {
                this.RedirectDefault("No tiene permisos para realizar " + operation);
            }
        }

        public void RedirectDefault()
        {
            // TODO: chequear la session
            RedirectDefault(string.Empty);
        }

        public void RedirectDefault(string message)
        {
            // TODO: chequear la session
            Response.Redirect(string.Format("/App/Default.aspx?message={0}", message), true);
        }

        protected void BindAuditory(IAuditable auditableEntity)
        {
            Control ctrlBox = FindControlRecursive(this, "txtAuditFechaCreacion");
            TextBox txtBox;
            if (ctrlBox != null)
            {
                txtBox = (TextBox)ctrlBox;
                txtBox.Text = auditableEntity.AuditFechaCreacion.ToString("dd/MM/yyyy HH:mm");
            }

            ctrlBox = this.FindControlRecursive(this, "txtAuditUserNameCreacion");
            if (ctrlBox != null)
            {
                txtBox = (TextBox)ctrlBox;
                txtBox.Text = auditableEntity.AuditUserNameCreacion;
            }

            ctrlBox = this.FindControlRecursive(this, "txtAuditUserNameModificacion");
            if (ctrlBox != null)
            {
                txtBox = (TextBox)ctrlBox;
                txtBox.Text = auditableEntity.AuditUserNameModificacion;
            }

            ctrlBox = this.FindControlRecursive(this, "txtAuditFechaModificacion");
            if (ctrlBox != null && auditableEntity.AuditFechaModificacion.HasValue)
            {
                txtBox = (TextBox)ctrlBox;
                txtBox.Text = auditableEntity.AuditFechaModificacion.Value.ToString("dd/MM/yyyy HH:mm");
            }
        }

        protected Control FindControlRecursive(Control rootControl, string controlID)
        {
            if (rootControl.ID == controlID) return rootControl;

            foreach (Control controlToSearch in rootControl.Controls)
            {
                Control controlToReturn =
                    FindControlRecursive(controlToSearch, controlID);
                if (controlToReturn != null) return controlToReturn;
            }
            return null;
        }

        ///// <summary>
        ///// Agrega las acciones de la pantalla en el menu
        ///// </summary>
        //protected abstract void AppendActionsToMenu();
    }
}